//package com.example.demo.controller;
//
//import com.example.demo.config.JacocoConfig;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.http.ResponseEntity;
//import org.springframework.web.bind.annotation.GetMapping;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RestController;
//
//import java.io.BufferedReader;
//import java.io.File;
//import java.io.InputStreamReader;
//import java.util.HashMap;
//import java.util.Map;
//
///**
// * JaCoCo覆盖率报告控制器
// * 提供API接口用于手动触发JaCoCo覆盖率数据的收集和报告生成
// */
//@RestController
//@RequestMapping("/api/jacoco")
//public class JacocoController {
//
//    @Autowired
//    private JacocoConfig jacocoConfig;
//
//    /**
//     * 保存当前的JaCoCo覆盖率数据
//     * @return 保存结果
//     */
//    @GetMapping("/dump")
//    public ResponseEntity<Map<String, Object>> dumpJacocoData() {
//        Map<String, Object> response = new HashMap<>();
//        boolean success = jacocoConfig.dumpJacocoData();
//
//        response.put("success", success);
//        response.put("message", success ? "JaCoCo覆盖率数据已保存" : "保存JaCoCo覆盖率数据失败");
//        response.put("timestamp", System.currentTimeMillis());
//
//        return ResponseEntity.ok(response);
//    }
//
//    /**
//     * 生成JaCoCo覆盖率报告
//     * @return 生成结果
//     */
//    @GetMapping("/report")
//    public ResponseEntity<Map<String, Object>> generateJacocoReport() {
//        Map<String, Object> response = new HashMap<>();
//
//        try {
//            // 首先保存当前的覆盖率数据
//            jacocoConfig.dumpJacocoData();
//
//            // 使用Maven命令生成报告
//            ProcessBuilder processBuilder = new ProcessBuilder();
//
//            // 根据操作系统选择正确的Maven命令
//            String mvnCommand = System.getProperty("os.name").toLowerCase().contains("win")
//                    ? "mvnw.cmd" : "./mvnw";
//
//            processBuilder.command(mvnCommand, "jacoco:report");
//            processBuilder.directory(new File(System.getProperty("user.dir")));
//
//            Process process = processBuilder.start();
//
//            // 读取命令输出
//            StringBuilder output = new StringBuilder();
//            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
//            String line;
//            while ((line = reader.readLine()) != null) {
//                output.append(line).append("\n");
//            }
//
//            // 等待命令执行完成
//            int exitCode = process.waitFor();
//
//            response.put("success", exitCode == 0);
//            response.put("message", exitCode == 0 ? "JaCoCo报告生成成功" : "JaCoCo报告生成失败");
//            response.put("exitCode", exitCode);
//            response.put("output", output.toString());
//            response.put("reportPath", "target/site/jacoco/index.html");
//            response.put("timestamp", System.currentTimeMillis());
//
//        } catch (Exception e) {
//            response.put("success", false);
//            response.put("message", "生成JaCoCo报告时出错: " + e.getMessage());
//            response.put("error", e.toString());
//            response.put("timestamp", System.currentTimeMillis());
//        }
//
//        return ResponseEntity.ok(response);
//    }
//
//    /**
//     * 获取JaCoCo覆盖率报告状态
//     * @return 报告状态
//     */
//    @GetMapping("/status")
//    public ResponseEntity<Map<String, Object>> getJacocoStatus() {
//        Map<String, Object> response = new HashMap<>();
//
//        // 检查覆盖率数据文件是否存在
//        File jacocoExec = new File("target/jacoco-runtime.exec");
//        boolean dataFileExists = jacocoExec.exists();
//
//        // 检查报告是否已生成
//        File jacocoReport = new File("target/site/jacoco/index.html");
//        boolean reportExists = jacocoReport.exists();
//
//        response.put("dataFileExists", dataFileExists);
//        response.put("dataFileSize", dataFileExists ? jacocoExec.length() : 0);
//        response.put("dataFileLastModified", dataFileExists ? jacocoExec.lastModified() : 0);
//
//        response.put("reportExists", reportExists);
//        response.put("reportLastModified", reportExists ? jacocoReport.lastModified() : 0);
//
//        response.put("timestamp", System.currentTimeMillis());
//
//        return ResponseEntity.ok(response);
//    }
//}

package com.example.demo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.management.MBeanServer;
import javax.management.ObjectName;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.lang.management.ManagementFactory;
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.ResponseEntity;

@RestController
@RequestMapping("/api/jacoco")
public class JacocoController {

    @GetMapping("/dump")
    public ResponseEntity<Map<String, Object>> dumpJacocoData() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 获取JaCoCo运行时MBean
            MBeanServer server = ManagementFactory.getPlatformMBeanServer();
            ObjectName name = new ObjectName("org.jacoco:type=Runtime");

            // 调用dump方法
            server.invoke(name, "dump", new Object[]{true}, new String[]{"boolean"});

            // 检查文件是否生成
            String destFilePath = System.getProperty("user.dir") + "/target/jacoco-runtime.exec";
            File destFile = new File(destFilePath);
            boolean success = destFile.exists();

            response.put("success", success);
            response.put("message", success ? "JaCoCo覆盖率数据已保存" : "保存JaCoCo覆盖率数据失败");
            if (success) {
                response.put("fileSize", destFile.length());
                response.put("filePath", destFilePath);
            }
            response.put("timestamp", System.currentTimeMillis());

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "收集JaCoCo覆盖率数据失败: " + e.getMessage());
            response.put("error", e.toString());
            response.put("timestamp", System.currentTimeMillis());
            
            return ResponseEntity.ok(response);
        }
    }

    @GetMapping("/status")
    public ResponseEntity<Map<String, Object>> getJacocoStatus() {
        Map<String, Object> response = new HashMap<>();

        try {
            // 检查覆盖率数据文件是否存在
            File jacocoExec = new File("target/jacoco-runtime.exec");
            boolean dataFileExists = jacocoExec.exists();

            // 检查报告是否已生成
            File jacocoReport = new File("target/site/jacoco/index.html");
            boolean reportExists = jacocoReport.exists();

            response.put("dataFileExists", dataFileExists);
            response.put("dataFileSize", dataFileExists ? jacocoExec.length() : 0);
            response.put("dataFileLastModified", dataFileExists ? jacocoExec.lastModified() : 0);

            response.put("reportExists", reportExists);
            response.put("reportLastModified", reportExists ? jacocoReport.lastModified() : 0);

            response.put("timestamp", System.currentTimeMillis());

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("error", "获取JaCoCo状态失败: " + e.getMessage());
            response.put("timestamp", System.currentTimeMillis());
            return ResponseEntity.ok(response);
        }
    }
    
    /**
     * 生成JaCoCo覆盖率报告
     * @return 生成结果
     */
    @GetMapping("/report")
    public ResponseEntity<Map<String, Object>> generateJacocoReport() {
        Map<String, Object> response = new HashMap<>();

        try {
            // 首先保存当前的覆盖率数据
            dumpJacocoData();

            // 使用Maven命令生成报告
            ProcessBuilder processBuilder = new ProcessBuilder();

            // 根据操作系统选择正确的Maven命令
            String mvnCommand = System.getProperty("os.name").toLowerCase().contains("win")
                    ? "mvnw.cmd" : "./mvnw";

            processBuilder.command(mvnCommand, "jacoco:report");
            processBuilder.directory(new File(System.getProperty("user.dir")));

            Process process = processBuilder.start();

            // 读取命令输出
            StringBuilder output = new StringBuilder();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                output.append(line).append("\n");
            }

            // 等待命令执行完成
            int exitCode = process.waitFor();

            response.put("success", exitCode == 0);
            response.put("message", exitCode == 0 ? "JaCoCo报告生成成功" : "JaCoCo报告生成失败");
            response.put("exitCode", exitCode);
            response.put("output", output.toString());
            response.put("reportPath", "target/site/jacoco/index.html");
            response.put("timestamp", System.currentTimeMillis());

        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "生成JaCoCo报告时出错: " + e.getMessage());
            response.put("error", e.toString());
            response.put("timestamp", System.currentTimeMillis());
        }

        return ResponseEntity.ok(response);
    }
}